package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Department;
import cn.wolfcode.mapper.DepartmentMapper;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * @author L5775
 */
@Service
public class DepartmentServiceImpl implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public void save(Department department) {
        //检查参数合法性
        //假设业务很复杂
        departmentMapper.insert(department);
    }

    @Override
    public void delete(Long id) {
        departmentMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Department department) {
        departmentMapper.updateByPrimaryKey(department);
    }

    @Override
    public Department get(Long id) {
        return departmentMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Department> listAll() {
        return departmentMapper.selectAll();
    }

    @Override
    public PageResult<Department> query(QueryObject qo) {
        int count = departmentMapper.selectForCount(qo);
        if (count == 0) {
            return new PageResult<>(qo.getCurrentPage(),qo.getPageSize(),count, Collections.emptyList());
        }
        //判断当前页是否大于总页数
        int totalPage = count % qo.getPageSize() == 0 ? count / qo.getPageSize()
                : count / qo.getPageSize() + 1;
        if (qo.getCurrentPage()>totalPage){
            //如果大于就设置当前页为最后一页
            qo.setCurrentPage(totalPage);
        }

        List<Department> departments = departmentMapper.selectForList(qo);
        return new PageResult<>(qo.getCurrentPage(),qo.getPageSize(),count,departments);
    }
}
